package com.tanhua.server.service;

import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.AdviceCommentLikesVo;
import com.tanhua.domain.vo.ContractVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class IMService {
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private FriendApi friendApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    
    /**
     * 接口名称：联系人添加 (添加友好)
     * 接口路径：POST/messages/contacts
     */
    public ResponseEntity<Object> addContacts(Long friendId) {
        //0. 获取登陆用户id
        Long userId = UserHolder.getUserId();
        //1. 保存好友关系到mongo
        friendApi.addContacts(userId, friendId);
        //2. 注册好友关系到环信
        huanXinTemplate.contactUsers(userId, friendId);
        return ResponseEntity.ok(null);
    }
    
    /**
     * 接口名称：联系人列表
     */
    public ResponseEntity<Object> contactsList(Integer page, Integer pagesize, String keyword) {
        //1. 调用Api服务查询用户好友列表
        PageResult pageResult = friendApi.findByPage(page, pagesize, UserHolder.getUserId());
        //2. 获取分页数据
        List<Friend> list = (List<Friend>) pageResult.getItems();
        //3. 定义返回的vo集合
        List<ContractVo> voList = new ArrayList<>();
        //4. 封装vo集合
        if (!CollectionUtils.isEmpty(list)) {
            for (Friend friend : list) {
                ContractVo vo = new ContractVo();
                vo.setId(friend.getUserId());
                vo.setUserId(friend.getFriendId().toString());
                // 根据好友id查询
                UserInfo userInfo = userInfoApi.findById(friend.getFriendId());
                BeanUtils.copyProperties(userInfo, vo);
                // 添加到集合
                voList.add(vo);
            }
        }
        //5. 设置vo集合到分页对象中并返回
        pageResult.setItems(voList);
        return ResponseEntity.ok(pageResult);
    }
    
    /**
     * 点赞列表（属于消息通知）
     */
    public ResponseEntity<Object> likes(Integer page, Integer pagesize) {
        return getObjectResponseEntity(page, pagesize, 1);
    }
    
    /**
     * （文字）评论列表（属于消息通知）
     */
    public ResponseEntity<Object> comments(Integer page, Integer pagesize) {
        return getObjectResponseEntity(page, pagesize, 2);
    }
    
    /**
     * 喜欢列表（属于消息通知）
     */
    public ResponseEntity<Object> loves(Integer page, Integer pagesize) {
        return getObjectResponseEntity(page, pagesize, 3);
    }
    
    
    /**
     * 抽取的公用方法，可根据查询类型而返回点赞、（文字）评论、点赞通知列表，并将其封装到分页对象里，放到统一响应类型里
     *
     * @param page        当前页
     * @param pagesize    页大小（一页显示多少条记录）
     * @param commentType 1-点赞 2文字评论 3-喜欢
     * @return
     */
    private ResponseEntity<Object> getObjectResponseEntity(Integer page, Integer pagesize, Integer commentType) {
        //1、当前登录的用户id
        Long userId = UserHolder.getUserId();
        //2、查询当前登录用户的动态的分页对象
        PageResult pageResult = publishApi.findByAlbum(userId, page, pagesize);
        //获取动态列表
        List<Publish> publishList = (List<Publish>) pageResult.getItems();
        
        //3 创建一个空列表，准备封装返回的列表数据
        List<AdviceCommentLikesVo> likesVoList = new ArrayList<>();
        
        //4 遍历动态列表，根据动态id，查询到评论id，再插到评论id所在评论记录的评论人的用户id，进而获取其用户信息UserInfo
        for (Publish publish : publishList) {
            //4.1 获取动态id
            String publishId = publish.getId().toString();
            //4.2 根据动态id查询到评论的分页对象
            PageResult comentPageResultVo = commentApi.adviceCommentsList(publishId, commentType, page, pagesize);
            //评论分页对象里获取评论列表
            List<Comment> commentList = (List<Comment>) comentPageResultVo.getItems();
            //4.3 遍历评论列表 得到评论人的用户id，根据其id获取其用户信息，再逐一封装到likesVoList空列表里
            for (Comment comment : commentList) {
                //去除用户自己对自己动态的点赞、评论、喜欢的操作
                if (!comment.getUserId().equals(userId)) {
                    Long commentUserId = comment.getUserId();
                    UserInfo userInfo = userInfoApi.findById(commentUserId);
                    AdviceCommentLikesVo AdviceCommentLikesVo = new AdviceCommentLikesVo();
                    AdviceCommentLikesVo.setId(comment.getId().toString());
                    AdviceCommentLikesVo.setAvatar(userInfo.getAvatar());
                    AdviceCommentLikesVo.setNickname(userInfo.getNickname());
                    AdviceCommentLikesVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(comment.getCreated()));
                    likesVoList.add(AdviceCommentLikesVo);
                    
                }
            }
        }
        pageResult.setItems(likesVoList);
        return ResponseEntity.ok(pageResult);
    }
    
}


















